package com.health.ts.controller;

import javax.annotation.PostConstruct;

import org.codehaus.groovy.control.CompilerConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.health.ts.constant.ApiResult;

import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(value = "Groovy脚本支持接口", tags = {"Groovy脚本支持接口"})
@RestController
@RequestMapping(value = "/api/groovy", produces= BaseController.JSON_UTF8)
public class GroovyScriptController extends BaseController {

    @Autowired
    private Binding groovyBinding;

    private GroovyShell groovyShell;

    @PostConstruct
    public void init(){
        GroovyClassLoader groovyClassLoader = new GroovyClassLoader(this.getClass().getClassLoader());
        CompilerConfiguration compilerConfiguration = new CompilerConfiguration();
        compilerConfiguration.setSourceEncoding("utf-8");
        groovyShell = new GroovyShell(groovyClassLoader, groovyBinding, compilerConfiguration);
    }

    @ApiOperation(value = "执行Groovy脚本", notes = "执行Groovy脚本")
    @RequestMapping(value = "/script/execute", method = RequestMethod.POST)
    public ApiResult execute(@RequestBody String scriptContent) {
        Script script = groovyShell.parse(scriptContent);
        return ApiResult.success(script.run());
    }
}
